package com.shujia.spark.core

import org.apache.spark.rdd.RDD
import org.apache.spark.storage.StorageLevel
import org.apache.spark.{SparkConf, SparkContext}

object Demo3Cache {
  def main(args: Array[String]): Unit = {


    //创建环境
    val conf = new SparkConf()
    //local[8]： 启动几个线程来执行我们的代码
    conf.setMaster("local[4]")
    conf.setAppName("cache")

    val sc = new SparkContext(conf)

    val studentRDD: RDD[String] = sc.textFile("data/students")

    /**
      * 1、统计班级的人数
      * 2、统计性别的人数
      * 3、统计年龄的人数
      *
      */

    val stuRDD: RDD[(String, String, Int, String, String)] = studentRDD
      .map(line => line.split(","))
      .map {
        case Array(id: String, name: String, age: String, gender: String, clazz: String) =>
          (id, name, age.toInt, gender, clazz)
      }


    /**
      * 多rdd进行缓存
      *
      */

    //默认的缓存级别是MEMORY_ONLY
    //stuRDD.cache()

    //可以手动设置缓存级别
    //stuRDD.persist(StorageLevel.MEMORY_AND_DISK_SER)


    //1、统计班级的人数
    val clazzNUmRDD: RDD[(String, Int)] = stuRDD
      .groupBy(stu => stu._5)
      .map {
        case (clazz: String, iter: Iterable[(String, String, Int, String, String)]) =>
          (clazz, iter.size)
      }

    clazzNUmRDD.foreach(println)


    //2、统计性别的人数
    val genderNUmRDD: RDD[(String, Int)] = stuRDD
      .groupBy(stu => stu._4)
      .map {
        case (gender: String, iter: Iterable[(String, String, Int, String, String)]) =>
          (gender, iter.size)
      }

    genderNUmRDD.foreach(println)

    //2、统计年龄的人数
    val ageNUmRDD: RDD[(Int, Int)] = stuRDD
      .groupBy(stu => stu._3)
      .map {
        case (age: Int, iter: Iterable[(String, String, Int, String, String)]) =>
          (age, iter.size)
      }

    ageNUmRDD.foreach(println)


    while (true) {

    }


  }

}
